package com.hdu;

import com.hdu.utils.JavaCodeGenerator;
import com.hdu.utils.JavaCompilerUtils;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.MalformedURLException;

public class Proxy {

    protected InvocationHandler h;

    public Proxy(InvocationHandler h) {
        this.h = h;
    }


    public static void main(String[] args) {
        String javaCode = JavaCodeGenerator.generateProxyJavaCode(ITeacherService.class);
        System.out.println(javaCode);
    }

    @SuppressWarnings("unchecked")
    public static <T> T newProxyInstance(ClassLoader loader,
                                          Class<T> targetClass,
                                          InvocationHandler h)
            throws IllegalArgumentException {
        generateClassFile(targetClass);
        Package aPackage = targetClass.getPackage();
        String packageName = aPackage.getName().toString();
        String packagePath = packageName.replace('.', File.separatorChar);
        // src\main\java\com\hdu\$Proxy_IStudentService.java
        String absoluteClassPath = "src\\main\\java\\" + packagePath + "\\$Proxy_" + targetClass.getSimpleName() + ".java";
        // com.hdu.HelloWorldClass
        String relativeClassPath = (packagePath + "\\$Proxy_" + targetClass.getSimpleName()).replace("\\", ".");
        try {
            return (T) JavaCompilerUtils.getObject(absoluteClassPath, relativeClassPath, loader, h);
        } catch (MalformedURLException | ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    public static void generateClassFile(Class<?> targetClass) {
        String proxyClassJavaCode = JavaCodeGenerator.generateProxyJavaCode(targetClass);
        Package aPackage = targetClass.getPackage();
        String packageName = aPackage.getName().toString();
        String packagePath = packageName.replace('.', File.separatorChar);
        File outputDir = new File("src/main/java/" + packagePath);
        if (!outputDir.exists()) {
            outputDir.mkdirs(); // 如果目录不存在，则创建它
        }
        String fileName = "$Proxy_" + targetClass.getSimpleName() + ".java";
        File file = new File(outputDir, fileName);
        try (FileWriter writer = new FileWriter(file)) {
            writer.write(proxyClassJavaCode);
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
